package com.xz.knowledgeDuplication.thread.sync;

/**
 * 不安全买票
 * @author 召
 * @date 2022-07-25 21:22:10
 */
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "小明").start();
        new Thread(buyTicket, "小红").start();
        new Thread(buyTicket, "黄牛").start();
    }

}

class BuyTicket implements Runnable {

    /**
     * 票数
     */
    private int ticketNums = 10;

    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加synchronized解决不安全问题,锁的是BuyTicket对象(当前对象)
     * @throws InterruptedException
     */
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        // 放大问题的发生性
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + " : " + ticketNums--);
    }
}